package com.springapp.mvc.dao;

import com.springapp.mvc.entity.Group;
import com.springapp.mvc.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by dbychkov on 19.12.2014.
 */
@Component
public class GroupDaoImpl implements GroupDao {

    @Autowired
    private JdbcTemplate template;

    public void setJdbcTemplate(JdbcTemplate template) {
        this.template = template;
    }

    @Override
    public List<Role> getRolesByGroupId(Long groupId) {
        String q = "SELECT r.id AS roleid, r.name AS rolename FROM  groups g  " +
                   "INNER JOIN group_role gr ON g.id = gr.group_id " +
                   "INNER JOIN roles r       ON gr.role_id = r.id  " +
                   "WHERE g.id = ?";
        return template.query(q, new RowMapper<Role>() {
            @Override
            public Role mapRow(ResultSet resultSet, int i) throws SQLException {
                Role result = new Role();
                result.setId(resultSet.getLong("roleid"));
                result.setName(resultSet.getString("rolename"));
                return result;
            }
        }, groupId);
    }

    @Override
    public long createGroup(String groupName) {
        template.update("INSERT INTO groups (name) values (?)", groupName);
        return template.queryForLong("select last_insert_id()");
    }

    @Override
    public Group getGroupById(Long id) {
        String q = "SELECT * FROM groups WHERE id = ?";
        List<Group> result = template.query(q,  Mappers.GROUP_MAPPER, id);
        return result.isEmpty() ? null : result.get(0);
    }

    @Override
    public Group getGroupByName(String name) {
        String q = "SELECT * FROM groups WHERE name = ?";
        List<Group> result = template.query(q,  Mappers.GROUP_MAPPER, name);
        return result.isEmpty() ? null : result.get(0);
    }

    @Override
    public List<Group> getAllGroups() {
        return template.query("SELECT * FROM groups", Mappers.GROUP_MAPPER);
    }
}
